<?php

//用户心愿单
namespace App\Http\Controllers\Admin\Mall;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;

class WishController extends BaseController
{
    /**
     * @api {get} /mall/wish/list 心愿单管理列表
     *
     * @apiGroup 个性商城-用户心愿单
     *
     * @apiParam {Int} cate_id 分类id
     * @apiParam {String} wish_user_code 许愿者ID
     * @apiParam {String} wish_nickname 许愿者昵称
     * @apiParam {String} finish_user_code 祝福（完成）者ID
     * @apiParam {String} finish_nickname 祝福（完成）者昵称
     * @apiParam {String} finish_date 祝福（完成）日期
     * @apiParam {String} product_name 商品名称
     * @apiParam {Int} days 天数
     * @apiParam {Int} price 价格
     * @apiParam {Int} status 状态：-1（默认）：不限制；0：未实现；1：已实现
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "user_id": 547900,
    "product_id": 24,
    "price_id": 24,
    "add_time": "2021-06-30 14:55:33", 许愿时间
    "finish_time": "2021-06-30 15:14:40", 祝福时间
    "finish_user": 547900,
    "status": 1, 状态：0未实现1已实现
    "wish_user_code": 617040, 许愿者ID
    "wish_nickname": "", 许愿者昵称
    "finish_user_code": 617040, 祝福者ID
    "finish_nickname": "", 祝福者昵称
    "product_name": "玛莎拉蒂", 商品名称
    "cate_name": "坐骑", 分类名称
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed9071a58f14.png", 图片
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed9071f2619d.svga", 动效
    "days": 7, 天数
    "price": 19999 价格
    }
    ],
    "first_page_url": "http://local.qipaoadmin/mall/wish/list?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/mall/wish/list?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/mall/wish/list",
    "per_page": 10,
    "prev_page_url": null,
    "to": 6,
    "total": 6
    }
    }
     */
    public function list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'cate_id' => 'integer|min:0',
                'wish_user_code' => 'integer',
                'wish_nickname' => 'string',
                'finish_user_code' => 'integer',
                'finish_nickname' => 'string',
                'finish_date' => 'date',
                'product_name' => 'string',
                'days' => 'integer|min:1',
                'price' => 'integer',
                'status' => 'integer|in:-1,0,1',
                'page_size' => 'integer|min:1',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $cateId = $request->cate_id ?? 0;
        $wishUserCode = $request->wish_user_code;
        $wishNickname = $request->wish_nickname;
        $finishUserCode = $request->finish_user_code;
        $finishNickname = $request->finish_nickname;
        $finishDate = $request->finish_date;
        $productName = $request->product_name;
        $days = $request->days;
        $price = $request->price;
        $status = $request->status ?? -1;
        $pageSize = $request->page_size ?? 10;

        $where = $whereFunc = $whereFunc2 = [];
        if ($cateId > 0) {
            $productIds = app('model_mall_products')
                ->select('id')
                ->where('category_id', $cateId)
                ->pluck('id')->toArray();
            $whereFunc = function ($query) use ($productIds) {
                $query->whereIn('product_id', $productIds);
            };
        }
        if ($wishUserCode) {
            $userId = app('model_user_data')->where('user_code', $wishUserCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($wishNickname) {
            $userId = app('model_user_data')->where('nickname', $wishNickname)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($finishUserCode) {
            $userId = app('model_user_data')->where('user_code', $finishUserCode)->value('user_id');
            $where[] = ['finish_user', '=', $userId];
        }
        if ($finishNickname) {
            $userId = app('model_user_data')->where('nickname', $finishNickname)->value('user_id');
            $where[] = ['finish_user', '=', $userId];
        }
        if ($finishDate) {
            $where[] = ['finish_time', '>=', strtotime($finishDate . ' 0:0:0')];
            $where[] = ['finish_time', '<=', strtotime($finishDate . ' 23:59:59')];
        }
        if ($productName) {
            $productId = app('model_mall_products')->where('title', 'like', '%' . $productName . '%')->value('id');
            $where[] = ['product_id', '=', $productId];
        }
        if ($days) {
            $priceIdsWhere = app('model_mall_products_price')->where('day', $days)->pluck('id')->toArray();
        }
        if ($price) {
            $priceIdsWhere2 = app('model_mall_products_price')->where('price', $price)->pluck('id')->toArray();
            if (isset($priceIdsWhere)) {
                $priceIdsWhere = array_intersect($priceIdsWhere, $priceIdsWhere2);
            } else {
                $priceIdsWhere = $priceIdsWhere2;
            }
        }
        if (isset($priceIdsWhere)) {
            $whereFunc2 = function ($query) use ($priceIdsWhere) {
                $query->whereIn('price_id', $priceIdsWhere);
            };
        }
        if ($status != -1) {
            $where[] = ['status', '=', $status];
        }

        $list = app('model_mall_wishlist')
            ->select('id', 'user_id', 'product_id', 'price_id', 'add_time', 'finish_time', 'finish_user', 'status')
            ->where($where)->where($whereFunc)->where($whereFunc2)
            ->paginate($pageSize)->toArray();

        //查询用户code和昵称
        $wishUserIds = array_column($list['data'], 'user_id');
        $finishUserIds = array_column($list['data'], 'finish_user');
        $userIds = array_unique(array_filter(array_merge($wishUserIds, $finishUserIds)));
        $users = app('model_user_data')
            ->select('user_id', 'user_code', 'nickname')
            ->whereIn('user_id', $userIds)->get()->toArray();
        $users = array_column($users, null, 'user_id');

        //查询商品信息
        $priceIds = array_column($list['data'], 'price_id');
        $priceIds = array_unique(array_filter($priceIds));
        $products = app('model_mall_products_price')->from('ln_mall_products_price as pp')
            ->select('pp.id', 'p.title as product_name', 'p.picture', 'p.special', 'pp.day', 'pp.price', 'c.title as cate_name')
            ->leftJoin('ln_mall_products as p', 'pp.product_id', '=', 'p.id')
            ->leftJoin('ln_mall_categories as c', 'p.category_id', '=', 'c.id')
            ->whereIn('pp.id', $priceIds)
            ->get()->toArray();
        $products = array_column($products, null, 'id');

        foreach ($list['data'] as &$v) {
            //许愿者code和昵称
            if (isset($users[$v['user_id']])) {
                $v['wish_user_code'] = $users[$v['user_id']]['user_code'];
                $v['wish_nickname'] = $users[$v['user_id']]['nickname'];
            } else {
                $v['wish_user_code'] = '';
                $v['wish_nickname'] = '';
            }
            //祝福者code和昵称
            if (isset($users[$v['finish_user']])) {
                $v['finish_user_code'] = $users[$v['finish_user']]['user_code'];
                $v['finish_nickname'] = $users[$v['finish_user']]['nickname'];
            } else {
                $v['finish_user_code'] = '';
                $v['finish_nickname'] = '';
            }
            //查询商品信息
            if (isset($products[$v['price_id']])) {
                $v['product_name'] = $products[$v['price_id']]['product_name'];
                $v['cate_name'] = $products[$v['price_id']]['cate_name'];
                $v['picture'] = $products[$v['price_id']]['picture'];
                $v['special'] = $products[$v['price_id']]['special'];
                $v['days'] = $products[$v['price_id']]['day'];
                $v['price'] = $products[$v['price_id']]['price'];
            } else {
                $v['product_name'] = '';
                $v['cate_name'] = '';
                $v['picture'] = '';
                $v['special'] = '';
                $v['days'] = '';
                $v['price'] = '';
            }
            //许愿时间和祝福时间
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            if ($v['status'] == 1) {
                $v['finish_time'] = date('Y-m-d H:i:s', $v['finish_time']);
            } else $v['finish_time'] = '';
        }
        return Response::sendData($list);
    }
}